import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  Upload,
  Modal,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { POINT_CONVERSION_COMPRESSED } from 'constants';

const FormItem = Form.Item;

const { TextArea } = Input;

@connect(({ user, shops, loading }) => ({
  user,
  shops,
  submitting: loading.effects['shops/submitShopForm'],
}))
@Form.create()
class BasicForms extends PureComponent {
  state = {
    uploading: false,
    previewVisible: false,
    previewImage: '',
    fileList: [],
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handleChange = ({ fileList }) => this.setState({ fileList });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  uploadPhoto = () => {
    const { fileList } = this.state;
    const { dispatch } = this.props;
    const formData = new FormData();
    console.log(fileList);
    fileList.forEach(file => {
      formData.append('picture', file);
    });
    dispatch({
      type: 'shops/uploadShopPhoto',
      payload: formData,
    });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'shops/fetchShopdetail',
    });
  }

  handleSubmit = e => {
    const { shops = {}, dispatch, form } = this.props;
    const { shopDetail = {} } = shops;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      console.log(values);
      if (!err) {
        values.id = shopDetail.id;
        dispatch({
          type: 'shops/submitShopForm',
          payload: values,
        });
      }
    });
  };

  beforeUpload = file => {
    this.setState(state => ({
      fileList: [...state.fileList, file],
    }));
  };

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const { shops = {}, submitting } = this.props;
    const { shopDetail = {} } = shops;
    const {
      form: { getFieldDecorator },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    return (
      <PageHeaderWrapper title={<FormattedMessage id="menu.shoplist.addshop" />}>
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.img' })}>
              <Upload
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
                customRequest={this.uploadPhoto}
                beforeUpload={this.beforeUpload}
              >
                {fileList.length >= 3 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </FormItem>

            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.name' })}>
              {getFieldDecorator('shop_name', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'shop.name.placeholder' }),
                  },
                ],
                initialValue: shopDetail.shop_name,
              })(<Input placeholder={formatMessage({ id: 'shop.name.placeholder' })} />)}
            </FormItem>

            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.address' })}>
              {getFieldDecorator('shop_address', {
                rules: [
                  {
                    message: formatMessage({ id: 'validation.title.required' }),
                  },
                ],
                initialValue: shopDetail.shop_address,
              })(<Input placeholder={formatMessage({ id: 'shop.address.placeholder' })} />)}
            </FormItem>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.contact' })}>
              {getFieldDecorator('shop_number', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.contact.placeholder' }),
                  },
                ],
                initialValue: shopDetail.shop_number,
              })(<Input placeholder={formatMessage({ id: 'shop.contact.placeholder' })} />)}
            </FormItem>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.website' })}>
              {getFieldDecorator('shop_website', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.website.placeholder' }),
                  },
                ],
                initialValue: shopDetail.shop_website,
              })(<Input placeholder={formatMessage({ id: 'shop.website.placeholder' })} />)}
            </FormItem>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.intro' })}>
              {getFieldDecorator('shop_intro', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.intro.placeholder' }),
                  },
                ],
                initialValue: shopDetail.shop_intro,
              })(
                <TextArea
                  style={{ minHeight: 32 }}
                  placeholder={formatMessage({ id: 'shop.intro.placeholder' })}
                  rows={4}
                />
              )}
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                <FormattedMessage id="form.save" />
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default BasicForms;
